import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:path/path.dart' as path;
import 'package:wallpaper_app/components/windows/window_title_bar.dart';
import 'rename_service.dart';

class FileRenameScreen extends StatefulWidget {
  const FileRenameScreen({super.key});

  @override
  State<FileRenameScreen> createState() => _FileRenameScreenState();
}

class _FileRenameScreenState extends State<FileRenameScreen> {
  final TextEditingController _startNumberController =
      TextEditingController(text: '1');
  final TextEditingController _prefixController =
      TextEditingController(); // 新增前缀控制器
  final TextEditingController _suffixController =
      TextEditingController(); // 新增后缀控制器
  final RenameService _renameService = RenameService();

  String? _selectedDirectory;
  List<FileSystemEntity> _files = [];
  List<String> _newFileNames = [];
  bool _isRenaming = false;
  String _statusMessage = '';
  bool _hasRenamedFiles = false;

  @override
  void dispose() {
    _startNumberController.dispose();
    _prefixController.dispose(); // 新增释放前缀控制器
    _suffixController.dispose(); // 新增释放后缀控制器
    super.dispose();
  }

  Future<void> _selectDirectory() async {
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath();

    if (selectedDirectory != null) {
      _loadFilesFromDirectory(selectedDirectory);
    }
  }

  void _loadFilesFromDirectory(String directoryPath) {
    setState(() {
      _selectedDirectory = directoryPath;
      _statusMessage = '选择的文件夹: $directoryPath';
      _hasRenamedFiles = false;

      final dir = Directory(directoryPath);
      // 只获取文件，不包括文件夹
      _files = dir.listSync().whereType<File>().toList();

      // 按照文件名排序
      _files.sort(
          (a, b) => path.basename(a.path).compareTo(path.basename(b.path)));

      // 预览新的文件名
      _generateNewFileNames();
    });
  }

  void _generateNewFileNames() {
    if (_files.isEmpty) {
      _newFileNames = [];
      return;
    }

    int startNumber = int.tryParse(_startNumberController.text) ?? 1;
    String prefix = _prefixController.text.isNotEmpty
        ? _prefixController.text
        : ''; // 判断是否设置了前缀
    String suffix = _suffixController.text.isNotEmpty
        ? _suffixController.text
        : ''; // 判断是否设置了后缀
    _newFileNames = _renameService.generateNewFileNames(_files, startNumber,
        prefix: prefix, suffix: suffix);
  }

  Future<void> _renameFiles() async {
    if (_files.isEmpty || _selectedDirectory == null) {
      setState(() {
        _statusMessage = '请先选择包含文件的文件夹';
      });
      return;
    }

    setState(() {
      _isRenaming = true;
      _statusMessage = '正在重命名文件...';
    });

    int startNumber = int.tryParse(_startNumberController.text) ?? 1;
    String prefix = _prefixController.text.isNotEmpty
        ? _prefixController.text
        : ''; // 判断是否设置了前缀
    String suffix = _suffixController.text.isNotEmpty
        ? _suffixController.text
        : ''; // 判断是否设置了后缀
    var result = await _renameService.renameFiles(_files, startNumber,
        prefix: prefix, suffix: suffix);

    setState(() {
      _isRenaming = false;
      _statusMessage =
          '重命名完成! 成功: ${result.successCount}, 失败: ${result.failCount}';
      _hasRenamedFiles = result.successCount > 0;

      // 如果有文件成功重命名，重新加载文件列表
      if (_hasRenamedFiles && _selectedDirectory != null) {
        _loadFilesFromDirectory(_selectedDirectory!);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    return Scaffold(
      body: Column(
        children: [
          WindowTitleBar(isBack: true),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                spacing: 10,
                children: [
                  Material(
                    color: theme.primaryContainer,
                    elevation: 3,
                    borderRadius: BorderRadius.all(Radius.circular(4)),
                    clipBehavior: Clip.hardEdge,
                    child: InkWell(
                      onTap: _selectDirectory,
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Row(
                          spacing: 10,
                          children: [
                            Icon(
                              Icons.folder,
                              size: 30,
                              color: const Color.fromARGB(255, 255, 196, 0),
                            ),
                            const Text('选择文件夹')
                          ],
                        ),
                      ),
                    ),
                  ),
                  if (_selectedDirectory != null) ...[
                    const Text(
                      '文件遵循递增数命名规则，请输入合法数字',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Row(
                      children: [
                        Expanded(
                          child: TextField(
                            controller: _startNumberController,
                            keyboardType: TextInputType.number,
                            decoration: const InputDecoration(
                              labelText: '起始数字',
                              border: OutlineInputBorder(),
                            ),
                            onChanged: (_) => setState(() {
                              _generateNewFileNames();
                            }),
                          ),
                        ),
                        const SizedBox(width: 8), // 调整间距
                        Expanded(
                          child: TextField(
                            controller: _prefixController, // 新增前缀输入框
                            decoration: const InputDecoration(
                              labelText: '前缀',
                              border: OutlineInputBorder(),
                            ),
                            onChanged: (_) => setState(() {
                              _generateNewFileNames();
                            }),
                          ),
                        ),
                        const SizedBox(width: 8), // 调整间距
                        Expanded(
                          child: TextField(
                            controller: _suffixController, // 新增后缀输入框
                            decoration: const InputDecoration(
                              labelText: '后缀',
                              border: OutlineInputBorder(),
                            ),
                            onChanged: (_) => setState(() {
                              _generateNewFileNames();
                            }),
                          ),
                        ),
                      ],
                    ),
                    ElevatedButton(
                      onPressed: _isRenaming ? null : _renameFiles,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green,
                        foregroundColor: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8), // 添加圆角
                        ),
                      ),
                      child: _isRenaming
                          ? const CircularProgressIndicator(color: Colors.white)
                          : const Text('开始重命名'),
                    ),
                    Text(
                      _statusMessage,
                      style: TextStyle(
                        color: _hasRenamedFiles ? Colors.green : theme.primary,
                      ),
                    ),
                    const Text('重命名预览:',
                        style: TextStyle(fontWeight: FontWeight.bold)),
                    Expanded(
                      child: _files.isEmpty
                          ? const Center(child: Text('没有找到文件'))
                          : ListView.builder(
                              itemCount: _files.length,
                              itemBuilder: (context, index) {
                                String originalName =
                                    path.basename(_files[index].path);
                                String newName = index < _newFileNames.length
                                    ? _newFileNames[index]
                                    : '未知';

                                return Card(
                                  elevation: 2,
                                  color: theme.primaryContainer,
                                  margin: const EdgeInsets.only(bottom: 8),
                                  shape: RoundedRectangleBorder(
                                    borderRadius:
                                        BorderRadius.circular(4), // 添加圆角
                                  ),
                                  child: ListTile(
                                    title: Text(
                                      originalName,
                                      style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16,
                                      ),
                                    ),
                                    subtitle: Text(
                                      '将重命名为: $newName',
                                      style: TextStyle(
                                        color: Colors.blueAccent,
                                        fontSize: 14,
                                      ),
                                    ),
                                    leading: const Icon(
                                      Icons.file_present_outlined,
                                      color: Colors.orange,
                                    ),
                                  ),
                                );
                              },
                            ),
                    ),
                  ] else ...[
                    const Expanded(
                      child: Center(
                        child: Text(
                          '批量重命名文件，请选择文件夹',
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
